package com.rcl.httpurlconnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/*
 * class title:
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/10/22.
 * PS: Not easy to write code, please indicate.
 */
public class ImageActivity extends AppCompatActivity {

    private ImageView mImageView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);

        initView();
        initHttp();
    }

    private void initView() {
        mImageView = findViewById(R.id.iv_image);
    }

    private void initHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url=new URL("http://192.168.0.123:3000/cc.png");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(5000);
                    urlConnection.connect();

                    InputStream inputStream = urlConnection.getInputStream();
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mImageView.setImageBitmap(bitmap);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
